# encoding: utf-8

from PyQt5.Qt import *
from widget.my_window import MyWindow
from widget.daoru_page.source_init_page.excl_source_init import ExclInitFunc
from xlrd import xldate_as_tuple
import datetime
import configparser
import os
from widget.info_box import InfoBox
import time
import _thread
from functools import partial
import json


class ChoiceExclSheetWindow(MyWindow):
    '''
    sqlserver配置 窗口
    '''
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.setAttribute(Qt.WA_StyledBackground, False)
        # 窗口置顶
        self.setWindowModality(Qt.ApplicationModal)
        # 父窗口实例对象
        self.my_parent_window = kwargs['my_parent']
        # excl文件路径
        self.excl_path = kwargs['excl_path']
        # excl工作簿
        self.workbook = kwargs['workbook']
        # 当前工作簿
        self.cur_sheet = None
        # 当前工作簿索引
        self.sheet_index = None
        # 窗口标题
        self.label_title = QLabel(self)
        self.label_title.resize(230, 40)
        self.label_title.setText('选择sheet')
        self.label_title.move(10, 5)
        # print('marc_init_sec: {0}'.format(self.marc_init_sec))
        self.setup_page()

    def setup_page(self):
        # 基础面板位置
        self.base_widget = QWidget(self)
        self.base_widget.setGeometry(0, 50, self.width(), self.height() - 50)

        # 第二行 ---------------------------------------------------
        self.choice_func_label = QLabel(text='选择sheet：')
        self.choice_func_label.setFixedWidth(120)
        self.choice_func_combox = QComboBox()
        self.choice_func_combox.setFixedWidth(300)
        self.choice_func_combox.setView(QListView())  # 通过setView和全局qss设置行高
        self.choice_func_combox.addItems(self.workbook.sheet_names())

        # self.choice_func_save_btn = QPushButton(text='保存')
        row1 = QHBoxLayout()
        row1.addWidget(self.choice_func_label)
        row1.addWidget(self.choice_func_combox)
        # row1.addWidget(self.choice_func_save_btn)
        row1.addStretch(1)  # 站位分割

        # 第三行, 初始化表格 ---------------------------------------------------
        self.table1 = QTableWidget()
        self.table1.setFixedWidth(870)
        self.table1.setFixedHeight(370)
        # 设置表格的列数为2列
        self.table1.setRowCount(11)
        # self.table1.setVerticalHeaderLabels(["第一列", "第二列"])
        # 设置表格每列的宽度
        self.table1.setColumnWidth(0, 120)
        self.table1.setColumnWidth(1, 120)
        self.table1.setColumnWidth(2, 120)
        self.table1.setColumnWidth(3, 120)
        self.table1.setColumnWidth(4, 120)
        self.table1.setColumnWidth(5, 120)
        self.table1.setColumnWidth(6, 50)
        # self.table1.setColumnWidth(2, 80)
        # print(field_list)
        self.choice_func_combox.currentIndexChanged.connect(self.refresh_table)

        # 表格监听表，如果表选择框改变，那么刷新表格
        # self.choice_func_combox.currentTextChanged.connect(self.refresh_table)
        row2 = QHBoxLayout()
        row2.addWidget(self.table1)

        # 最后一行 (底部常规按钮) ---------------------------------------------------
        self.okButton = QPushButton(text='确定')
        self.okButton.clicked.connect(self.excl_to_qapp)
        self.cancelButton = QPushButton(text="取消")
        self.cancelButton.clicked.connect(self.close_btn.click)
        row_last = QHBoxLayout()
        row_last.addStretch(1)  # 站位分割
        row_last.addWidget(self.okButton)
        row_last.addWidget(self.cancelButton)

        # 行插入列，并调整间隔 ---------------------------------------------------
        vbox = QVBoxLayout()
        vbox.addLayout(row1)
        vbox.addStretch(2)  # 站位分割
        vbox.addLayout(row2)
        vbox.addStretch(10)  # 站位分割
        vbox.addLayout(row_last)

        self.base_widget.setLayout(vbox)
        self.refresh_table(0)

    def refresh_table(self, index):
        '''
        刷新表格
        :return:
        '''
        self.cur_sheet = self.workbook.sheet_by_index(index)
        self.sheet_index = index
        if not self.cur_sheet:
            return

        # 第一行数据
        # 获取首行数据抛出IndexError时将整个表置空
        try:
            # self.table1.setColumnCount(row_count)
            # 如果最大行数超过11，就获取11条，否则获取全部行
            row_count = self.cur_sheet.nrows if self.cur_sheet.nrows < 11 else 11
            # 设置表行数
            self.table1.setRowCount(row_count)
            # 第一行是字段名，最大列数以字段名（第一行）为准
            field_name_list = self.cur_sheet.row_values(0)
            col_count = len(field_name_list)
            # 设置表列数
            self.table1.setColumnCount(col_count)
            # 表头设置为第一行 字段名
            self.table1.setHorizontalHeaderLabels(field_name_list)
            # print('row_count: {0}'.format(row_count))
            # 表内容设置为其余行 字段内容
            for i in range(row_count):
                # 将第二行到最后一行放到表中
                if i != row_count-1:
                    for k in range(col_count):
                        print(i, ' + ', k)
                        cell_field = self.cur_sheet.cell(i+1, k)
                        if cell_field.ctype == 3:
                            # 转成datetime对象
                            date = datetime.datetime(*xldate_as_tuple(cell_field.value, 0))
                            cell_value = date.strftime('%Y-%m-%d %H:%M:%S')
                        else:
                            cell_value = str(cell_field.value)
                        self.table1.setItem(i, k, QTableWidgetItem(cell_value))
                else:
                    for k in range(col_count):
                        self.table1.setItem(i, k, QTableWidgetItem('...'))
        except IndexError as e:
            print(e)
            self.table1.setRowCount(11)
            self.table1.setColumnCount(11)
            self.table1.clear()

    def excl_to_qapp(self):
        '''
        将对应sheet下的excl挂载到qApp上
        :return:
        '''
        self.excl_func = ExclInitFunc(self.excl_path, self.cur_sheet, self.sheet_index)
        self.excl_func.excl2qApp()
        # print(self.cur_sheet.name)
        self.my_parent_window.daoru_input1.setText('[{0}] - [{1}]'.format(self.excl_path, self.cur_sheet.name))
        self.close()

    def keyPressEvent(self, QKeyEvent):  # 键盘某个键被按下时调
        '''
        按下 ESC关闭当前页
        :param QKeyEvent:
        :return:
        '''
        # 参数1  控件
        if QKeyEvent.key() == Qt.Key_Escape:  # 判断是否按下了ESC键
            self.close_btn.click()